'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 副本星星奖励
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var Code = require('../../../consts/code');
var moduleType = require('../../../consts/moduleType');
var operationType = require('../../../consts/operationType');
var copyConf = require('../../../config/copyConf');
var rewardService = require('../../../services/rewardService');
var PlayerManager = require('../../../libs/playerManager');
var genRewardService = require('../../../services/genRewardService');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

/**
 * 总星数奖励
 *
 */
Handler.prototype.reward = function (msg, session, next) {
    var role_id = session.uid;
    var main_copy_id = msg.main_copy_id;
    var box_position = msg.box_position;
    if (!main_copy_id || !box_position) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var reward_list = [];
    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['role', 'copy', 'bag', 'build', 'task', 'daily_task', 'achieve', 'tech', 'sevenDayActivity', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var copy_model = player_manager.copy;

                var total_star_num = copy_model.getTotalStarNum(main_copy_id);
                var star_conf = copyConf.getCopyStarConf(main_copy_id, box_position);

                // 判断星星数是不是已经达到领取
                if (total_star_num < star_conf.star_num) {
                    return next(null, {
                        code: Code.COPY_STAR_NUM_NOT_ENOUGH
                    });
                }

                // 是否重复领取
                if (!copy_model.addStarReward(main_copy_id, box_position)) {
                    return next(null, {
                        code: Code.COPY_BOX_HAVE_RECEIVED
                    });
                }

                var reward = genRewardService.generateReward(star_conf);
                rewardService.addRewardToRole(player_manager, reward, moduleType.MDL_COPY, operationType.OPR_COPY_STAR_REWARD);
                reward_list.push(reward);
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    reward_list: reward_list
                }
            });
        }
    );
};
